<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      >
<head th:replace="fragments/tabhead::headc">
</head>

<body>
<th:block layout:fragment="content">
<!-- 头部 -->
<div style="margin-top:10px">
  <form class="layui-form search" id="headForm">
  <input type="hidden" id="StockInboundOrderId" name="id" th:value="${StockInboundOrder.id}"/>
  <input type="hidden" id="companyid" name="companyid" th:value="${StockInboundOrder.companyId}"/>
  <div class="layui-form-item layui-elem-quote">
    
   <div class="layui-inline">
      <label class="layui-form-label" style="width:100px">物料编码</label>
      <div class="layui-input-inline" style="width:150px">
        <input type="tel" name="materiaCode" class="layui-input" placeholder="请输入物料编码"/>
      </div>
    </div>
     <div class="layui-inline">
      <label class="layui-form-label" style="width:60px">品牌</label>
      <div class="layui-input-inline" style="width:100px">
        <input type="tel" name="brand" class="layui-input" placeholder="请输入品牌"/>
      </div>
    </div>
	
    <div class="layui-inline" style="float:right;">
      <div class="layui-input-inline" style="width:60px;">
        <button class="layui-btn" id="searchBtn" type="button">查询</button>
      </div>
      <div class="layui-input-inline" style="width:60px;" th:if="${StockInboundOrder.status=='0'}">
     	<button class="layui-btn" id="saveBtn" type="button">保存</button>
      </div>
      <div class="layui-input-inline" style="width:60px;" th:if="${StockInboundOrder.status=='0'}">
     	<button class="layui-btn layui-btn-danger" id="removeBtn" type="button">删除</button>
      </div>
      
    </div>
    
  </div>
 </form>
</div>

<div  style="overflow-x:auto;">
 <form  class="layui-form" action="" id="contentForm" lay-filter="contentForm">
	
</form>
</div>
<script>
var materialDialogIdx,trobj;
$(function(){
	
	layui.use(['form','layer','laytpl'], function(){
		var form = layui.form;
		 //获取原来的添加的数据
		 var data = $("#headForm").serializeJson();
		$("#contentForm").load("/stock/saleinbound/order-details",data,function(data){
			$("#contentTab tbody").append($("#blankTpl tr").parent().html());
			form.render();
		});
		
		
		//物料获得焦点时弹出对话框选择物料
		$("#contentForm").on("focus","input[name='materialCode']",function(){
			trobj = $(this).parents("tr");
			$.post('/stock/inbound/detail/selectmaterials', {}, function(str){
				materialDialogIdx=layer.open({
									id:"materialDialog",
									title:"物料选择",
								    type: 1,
								    maxmin :true,
								    area: ['1000px', '600px'],
								    content: str,//注意，如果str是object，那么需要字符拼接。
								    zIndex:10
							  });
			});
		});
		
		//结算方式选择事件绑定
		form.on("select(statementTypeId)",function(data){
			var $dom = $(data.elem);
			var $option = $dom.find("option[value='"+data.value+"']");
			var $tr = $dom.parent().parent();
			$tr.find("td[name='settlementDay'] span").html($option.attr("data-days"))
			.end().find("td[name='settlementCurrency'] span").html($option.attr("data-currencyName"))
			.end().find("td[name='settlementExchangeRate'] span").html($option.attr("data-exchargeRate"))
		});
		
		//查询按钮点击
		$("#searchBtn").click(function(){
			var data = $("#headForm").serializeJson();
			$("#contentForm").load("/stock/inbound/detail/order-details",data,function(data){
				$("#contentTab tbody").append($("#blankTpl tr").parent().html());
				form.render();
			});
		});
		
		 form.on('submit(contentForm)', function(data){
			 	var data = {};
				data["billid"]=$("#billid").val();
				data["companyid"]=$("#companyid").val();
				data["billno"]=$("#billno").val();
				data["supplierid"] = $("#supplierid").val();
				data["sourceOrderId"] = $("#sourceOrderId").val();
				data["sourceOrderNo"] = $("#sourceOrderNo").val();
				var items = [];
				var $trs = $("#contentTab tbody tr");
				if($trs.size()<=1) {
					layer.msg("没有添加物料！");
					return false;
				}
				for(var i=0;i<$trs.size();i++){
					var $tr = $trs.eq(i);
					var id = $tr.find("input[name='id']").val();
					var material_id= $tr.find("input[name='materialId']").val()==''?-1:$tr.find("input[name='materialId']").val();
// 				    var settlement_id = $tr.find("select[name='inStorage'] option:selected").val();
				    var price = $tr.find("input[name='price']").val()==''?-1: parseInt($tr.find("input[name='price']").val())*10000;
				    var reAccount = $tr.find("input[name='reAccount']").val();//应收量
				    var actualDelivery = $tr.find("input[name='actualDelivery']").val();//已收量
				    var acAccount = $tr.find("input[name='acAccount']").val();//本次数量
				    var isGift = $tr.find("select[name='isGift'] option:selected").val()==''?0:$tr.find("select[name='isGift'] option:selected").val();
				   	var toRecord = $tr.find("input[name='toRecord']").val();
				   	var storeageId = $tr.find("select[name='storeageId'] option:selected").val()
				   	console.log("storeageId="+storeageId);
				    if(material_id !=-1&&reAccount !=''&&acAccount !=''&&storeageId != -1){
					    items.push({
					    	id:id,
					    	materialId:material_id,
					    	receivableAccount:reAccount,
					    	price:price,
					    	acceptedAccount:actualDelivery,
					    	actualAccount:acAccount,
					    	isGift:isGift,
					    	toRecord:toRecord,
					    	storeageId:storeageId
					    });
				    }else{
				    	console.log("$trs.size()="+$trs.size());
				    	if(i==$trs.size()-1){
				    		continue;
				    	}
				    	if(material_id== -1){
				    		layer.msg("数据第"+(i+1)+"行物料没有选择");
				    	}else if(storeageId==-1) {
				    		layer.msg("数据第"+(i+1)+"行仓库没有填写");
				    	}else if(price==-1){
				    		layer.msg("数据第"+(i+1)+"行价格没有填写")
				    	}else if(reAccount=='') {
				    		layer.msg("数据第"+(i+1)+"行订单数量没有填写");
				    	}else if(acAccount=='') {
				    		layer.msg("数据第"+(i+1)+"行退货数量没有填写");
				    	}
				    	return false;
				    }
				}
				data["items"] = items;
				$.ajax({url:"/stock/inbound/detail/edit-orderdetail",
						data:JSON.stringify(data),
						type:"post",
						contentType:"application/json",
						success:function(data){
							if(data.code==200){
								layer.msg("数据保存成功！");
							}else{
								layer.msg(data.message);
							}
						}});
			return false;
		 });
		 
		//保存按钮事件
		$("#saveBtn").click(function(){
// 			console.log("hello");
			$("#contentForm").submit();
		});
		
		//删除按钮事件
		$("#removeBtn").click(function(){
			//获取所有的checkbox
			var checkedBox = $("#contentTab").find('tbody input[type="checkbox"]:checked');
			var removeids = [];//删除的id数组
			checkedBox.each(function(index, item){
				   var id = $(item).parents('tr').find("input[name='id']").val();
				   if(id!=null&&id!=''){
					   //获取所有的id列表
					   removeids.push(id);
				   }
		           $(item).parents("tr").remove();
		         
		     }); 
			if(removeids.length==0){
				layer.msg("未有勾选的记录！");
				return false;
			}
			var data = {};
			data['ids'] = removeids;
			$.ajax({
	             type: "post",
	             url: "/stock/inbound/detail/remove",
	             data: JSON.stringify(data),
	             type:"post",
				 contentType:"application/json",
	             success: function(data){
	             	if(data.code==200){
	             		layer.msg(data.message)
	             	}else{
	             		layer.msg(data.message)
	             	}
	             }
			});
		});
		
		//复选框表头操作
		form.on("checkbox(headCheckBox)",function(data){
			
			 var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]');  
	            child.each(function(index, item){  
	              item.checked = data.elem.checked;  
	            });  
	            form.render('checkbox'); 
		});
		
	});
	
	$("body").on("blur","#contentTab input[name='price']",function(){
		console.log("price")
		var $tr = $(this).parent().parent();
		var num = $tr.find("input[name='num']").val();
		setTaxinfo($tr,num,$(this).val());
	}).on("blur","#contentTab input[name='num']",function(){
		console.log("num")
		var $parent = $(this).parent().parent();
		var price = $parent.find("input[name='price']").val();
		setTaxinfo($parent,$(this).val(),price);
	});
	

	function setTaxinfo($tr,num,price){
		if(price&&num){
			var excludingTaxpriceTotal = num*price;
			console.log(price+"***"+num+"**"+excludingTaxpriceTotal)
			var taxRate = (parseFloat($tr.find("td[name='taxRate'] span").html())/100).toFixed(4);
			var taxPrice = parseFloat(excludingTaxpriceTotal*taxRate).toFixed(2);
			var tax = parseFloat(taxRate*excludingTaxpriceTotal).toFixed(2);
			var totalPrice = parseFloat(excludingTaxpriceTotal) + parseFloat(tax);
			$tr.find("td[name='taxPrice'] span").html(parseFloat(totalPrice/num).toFixed(2))
				.end().find("td[name='tax'] span").html(tax)
				.end().find("td[name='excludingTaxPriceTotal'] span").html(excludingTaxpriceTotal)
				.end().find("td[name='totalPrice']").html(totalPrice.toFixed(2));
		}
	}
});

</script>
<!--<div th:replace="/department/model::modelDiv"></div>-->
</th:block>
</body>
</html>